package com.bob.web.common.interceptor;

import com.bob.web.common.constant.SystemHoldContext;
import com.bob.web.entity.system.Admin;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by admin on 2017/7/5.
 */
public class LoginInterceptor implements HandlerInterceptor {

    public static final String USER_KEY = "_user";

    public static final String LOGIN_URL = "/user/login";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        //TODO 杨波 临时这样写一下，后面可以改成放在redis中或者session中
        if(SecurityUtils.getSubject().isAuthenticated()) {
            Admin admin = (Admin) SecurityUtils.getSubject().getSession(false).getAttribute(USER_KEY);
            if(admin != null) {
                SystemHoldContext.setCurrentUser(admin);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //判断在本地线程存储空间中是否有用户，有就放在session中
        if(SecurityUtils.getSubject().isAuthenticated()) {
            if(SecurityUtils.getSubject().getSession().getAttribute(USER_KEY)==null && SystemHoldContext.getCurrentUser() != null) {
                SecurityUtils.getSubject().getSession().setAttribute(USER_KEY, SystemHoldContext.getCurrentUser());
            }
        }

        //登出的时候清除session
//        if(SystemHoldContext.getCurrentUser() != null && Admin.STATUS_SIGN_OUT.equals(SystemHoldContext.getCurrentUser().getStatus())) {
//            SecurityUtils.getSubject().getSession().removeAttribute(USER_KEY);
//        }
    }

    //TODO 杨波 这里可能需要优化 可以利用shiro自身的subject去处理这种逻辑
    //TODO 杨波 这里是完成请求后的回调，所以不能用来处理session，因为这时候，response已经返回了
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        //判断在本地线程存储空间中是否有用户，有就放在session中
//        if(SecurityUtils.getSubject().getSession().getAttribute(USER_KEY)==null && SystemHoldContext.getCurrentUser() != null) {
//            request.getSession().setAttribute(USER_KEY, SystemHoldContext.getCurrentUser());
//        }
        //登出的时候清除session
//        if(SystemHoldContext.getCurrentUser() != null && Admin.STATUS_SIGN_OUT.equals(SystemHoldContext.getCurrentUser().getStatus())) {
//            SecurityUtils.getSubject().getSession().removeAttribute(USER_KEY);
//        }
    }
}
